package com.imodia.checkoo.service.impl;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.hsq.commons.util.db.GenericIbatisDao;
import com.hsq.commons.util.db.annotation.SqlSpace;
import com.imodia.checkoo.bean.CmsDocumentInfoBean;
import com.imodia.checkoo.service.CmsDocumentInfoService;

@SqlSpace(spaceName = "cmsdocumentinfo")
@Service
public class CmsDocumentInfoServiceImpl extends
		GenericIbatisDao<CmsDocumentInfoBean, Integer> implements
		CmsDocumentInfoService {
	
	private static final Log log = LogFactory.getLog(CmsDocumentInfoServiceImpl.class);

	public List<String> getTableField(String objectName) {
		Connection conn = null;
		ResultSet rs = null;
		Statement stmt = null;
		List<String> list = new ArrayList<String>();
		try {
			conn = super.getSqlMapClientTemplate().getDataSource()
					.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from " + objectName + " limit 1");
			ResultSetMetaData rsmd = rs.getMetaData();
			int numberOfColumns = rsmd.getColumnCount();
			log.debug("numberOfColumns:" + numberOfColumns);
			for (int i = 1; i <= numberOfColumns; i++) {
				String colName = rsmd.getColumnName(i);
				log.debug(colName);
				if (colName.startsWith("ext_")) {
					list.add(colName);
				}
			}
		} catch (DataAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				stmt.close();
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// Collections.sort(list);
		return list;
	}

	public int isExistTable(String tableName) {
		ResultSet rs = null;
		Connection conn = null;
		DatabaseMetaData dbmd = null;
		try {
			conn = this.getSqlMapClientTemplate().getDataSource()
					.getConnection();
			dbmd = conn.getMetaData();
			rs = dbmd.getTableTypes();
			rs = dbmd.getTables(null, null, tableName, null);
			if (rs != null && rs.next()) {
				return 1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				rs.close();
				dbmd = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

}